<template>
  <div class="dj">
    <div class="search">
      <template>
        <el-date-picker v-model="date" style="margin-right: 10px;" type="daterange" :align="'right'" unlink-panels
          value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期"
          :picker-options="pickerOptions" @change="getTableOne" />
        <el-select v-if="sjdwList" v-model="query.parentIds" style="margin-right: 10px;" filterable multiple
          placeholder="请选择上级单位" @change="sjdwChange">
          <el-option v-for="(item,index) in sjdwList" :key="index" :label="item.parentName" :value="item.parentId" />
        </el-select>
        <el-select v-if="query.parentIds.length" v-model="query.deptIds" filterable style="margin-right: 10px;" multiple
          placeholder="请选择点检单位">
          <el-option v-for="(item,index) in dataList.filter(f=>query.parentIds.includes(f.parentId))" :key="index"
            :label="item.deptName" :value="item.deptId" />
        </el-select>
        <el-select v-model="query.dictCodes" style="margin-right: 10px;" multiple placeholder="请选择点检情况">
          <el-option v-for="d in dictionaries[query.szm]" :key="d.dictCode" :label="d.dictLabel" :value="d.dictCode" />
        </el-select>
      </template>
      <el-button v-no-more-click type="primary" plain @click="getTableOne">搜索</el-button>
      <el-button type="success" plain @click="excel">导出</el-button>
      <!-- <el-button type="info" plain @click="switchVal = !switchVal">{{switchVal?'关闭':'显示'}}图表</el-button> -->
    </div>
    <list-table v-if="dataList.length > 0 && cssz.length>0" ref="Ltable" class="dj-table"
      :is-lazy-loading="isLazyLoading" :data-list="dataList" :cssz="cssz" :date-list="dateList" :len="len"
      :is-type="isType" @addForm="addForm" />
    <div v-if="sjdw.length>0" class="xbg">
      <el-table :data="sjdw" :border="true" style="width: 100%">
        <el-table-column label="上级部门" width="360" fixed sortable>
          <template slot-scope="scope">
            <span>{{ scope.row.parentName }}</span>
            <span style="font-weight: 600;color: red;">{{ `(${scope.row.num})` }}</span>
          </template>
        </el-table-column>
        <el-table-column v-for="time in dateList" :key="time" :label="time" :width="110">
          <template slot-scope="scope">
            <div style="font-weight: 600;color: red;">{{ scope.row.error[time] }}</div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 拉练添加 -->
    <el-dialog v-if="ll_lr" title="拉练结果" :visible.sync="ll_lr" width="40%">
      <!-- 类型 -->
      <el-form ref="form" :model="ll_djlx" label-width="120px" label-height="220px">
        <el-form-item label="点检类型">
          <el-select v-model="ll_djlx['type']" placeholder="请选择拉练类型">
            <el-option v-for="d in dictionaries['ll_djlx']" :key="d.dictCode" :label="d.dictLabel"
              :value="d.dictLabel" />
          </el-select>
        </el-form-item>
        <el-form-item label="点检内容">
          <!-- 内容 -->
          <el-input v-model="ll_djlx['jgms']" type="textarea" :rows="1" placeholder="拉练内容" />
        </el-form-item>
        <el-form-item label="用时">
          <!-- 用时 -->
          <el-input v-model="ll_djlx['time']" type="text" placeholder="拉练用时" />
        </el-form-item>
        <el-form-item label="是否达标">
          <!-- 达标 -->
          <el-select v-model="ll_djlx['dict_code']" placeholder="是否达标" @change="$event=>isChildren($event,item)">
            <el-option v-for="d in dictionaries[query.szm]" :key="d.dictCode" :label="d.dictLabel"
              :value="d.dictLabel" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-no-more-click type="primary" @click="ll_bc">保存</el-button>
      </div>
    </el-dialog>
    <!-- 整体添加 -->
    <el-dialog v-if="dialogFormVisible" :title="form.post === 'updateRhtxdj' ? '编辑' : '录入'"
      :visible.sync="dialogFormVisible" width="40%">
      <el-form ref="form" :model="form" label-width="120px" label-height="220px">
        <el-form-item v-for="(item,csszIndex) in cssz" :key="csszIndex" :label="item.tips">
          <!-- 输入框 -->
          <el-input v-if="item.type === 'input'" v-model="form[item.name]" :placeholder="item.placeholder"
            style="width: 220px;" />
          <!-- 特殊选择 -->
          <template v-if="item.name === 'jgms'">
            <div v-if="query.szm === 'll'">
              <el-button @click="ll_djlx_add">新增</el-button>
              <div v-for="(v,o) in ll_djlx_jh" :key="o">
                <div>点检类型：{{v.type}}</div>
                <div>点检内容：{{v.jgms}}</div>
                <div>用时：{{v.time}}</div>
                <div>是否达标：{{v.dict_code}}</div>
                <div>
                  <el-button type="text" @click="ll_edit(v,o)">编辑</el-button>
                  <!-- 删除 -->
                  <el-button style="color:red" type="text" @click="ll_djlx_jh.splice(i,1)">删除</el-button>
                </div>
              </div>
            </div>
            <el-input v-else v-model="form[item.name]" type="textarea" :rows="4" :placeholder="item.placeholder" />
          </template>
          <el-select v-if="item.name ==='deptId'" v-model="form[item.name]" :placeholder="item.placeholder">
            <el-option v-for="(item1,index) in dataList" :key="index" :label="item1.deptName" :value="item1.deptId" />
          </el-select>
          <div v-if="item.name ==='dictCode'">
            <el-select v-model="form[item.name]" :placeholder="item.placeholder"
              @change="$event=>isChildren($event,item)">
              <el-option v-for="d in dictionaries[query.szm]" :key="d.dictCode" :label="d.dictLabel"
                :value="d.dictCode" />
            </el-select>
            <el-date-picker v-if="datesShow" v-model="form[item.children.name]" style="margin-top: 10px"
              value-format="yyyy-MM-dd HH:mm" type="datetimerange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" />
          </div>
          <el-select v-if="item.name ==='cddw'" v-model="form[item.name]" :placeholder="item.placeholder">
            <el-option v-for="d in dictionaries['qz_cddw']" :key="d.dictCode" :label="d.dictLabel"
              :value="d.dictCode" />
          </el-select>
          <el-select v-if="item.name ==='djr'" v-model="form[item.name]" :placeholder="item.placeholder">
            <el-option v-for="u in userList.filter(f=>f.userId!=1)" :key="u.userId" :label="u.nickName"
              :value="u.userId" />
          </el-select>
          <div v-if="item.name === 'lrTime'">
            <!-- 当前时间 -->
            <el-date-picker v-model="form[item.name]" type="datetime" :placeholder="item.placeholder"
              value-format="yyyy-MM-dd HH:mm" :picker-options="{ disabledDate: dateOptions }" />
          </div>
        </el-form-item>
        <el-form-item v-if="query.szm === 'll'" label="点检民警">
          <el-input v-model="form['mj']" placeholder="请输入点检民警" style="width: 220px;" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="form.post == 'updateRhtxdj'" v-no-more-click type="danger" @click="deleteDj">删除</el-button>
        <el-button v-no-more-click type="primary" :loading="pLoading" @click="postForm">
          {{ form.post === 'updateRhtxdj' ? '更新' : '上传' }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import {
    addRhtxdj,
    updateRhtxdj,
    delRhtxdj
  } from '@/api/rhtx/rhtxdj'
  import {
    listUser
  } from '@/api/system/user'
  import {
    getTable
  } from '@/api/rhtx/ExcelTable'
  import {
    mixins
  } from '../xsqpcs'
  import listTable from './component/list.vue'
  export default {
    name: 'TableList',
    components: {
      listTable
    },
    mixins: [mixins],
    props: {
      type: {
        type: String,
        require: true,
        default: () => ''
      }
    },
    data() {
      const id = this.$route.params.id
      return {
        ll_djlx_i: null,
        ll_lr: false,
        ll_djlx: {},
        ll_djlx_jh: [],
        len: 1,
        // nowDateO: new Date(),
        isType: 0,
        h: 'auto',
        cssz: undefined,
        sjdw: [],
        sjdwList: [],
        djdw: undefined,
        switchVal: false, // 图表
        pLoading: false, // 上传加载
        exitData: {}, // 编辑对象
        dialogFormVisible: false, // 信息弹窗
        loading: false, // 初始化加载
        date: [], // 初始时间
        userList: [],
        query: {
          tableId: id,
          szm: this.$route.query.szm,
          parentIds: [],
          deptIds: [],
          dictCodes: [],
          ll_djlx: []
        },
        dataList: [],
        dateList: [],
        datesShow: false,
        dictionaries: {}, // 字典
        form: {
          mj: undefined,
          name: undefined,
          deptId: undefined,
          dictCode: undefined,
          jgms: undefined,
          djr: undefined,
          cddw: undefined,
          lrTime: undefined,
          remark: undefined,
          tableId: undefined,
          rhtxdjId: null,
          post: undefined,
          wgsj: undefined,

        },
        isF: undefined
      }
    },
    computed: {
      isLazyLoading() {
        return this.date[0] === this.date[1]
      }
    },
    created() {
      this.date = this.getOneDay()
      this.getTableOne()
      this.getDictsList()
      this.getUserlist()
    },
    methods: {
      // 拉练结果保存
      ll_bc() {
        // 如果ll_djlx是个对象存在没有填写的就提示填写
        let isNull = false
        // 对象换数组
        Object.keys(this.ll_djlx).forEach(item => {
          if (!this.ll_djlx[item] && !isNull) {
            isNull = true
          }
        })
        if (isNull) {
          return this.$message({
            message: '请填写完整',
            type: 'error'
          })
        }
        if (this.ll_djlx_i != null) {
          this.ll_djlx_jh[this.ll_djlx_i] = this.ll_djlx
          this.ll_djlx_i = null
        } else {
          this.ll_djlx_jh.push(this.ll_djlx)
        }
        this.ll_lr = false
      },
      ll_edit(v, i) {
        this.ll_djlx_i = i
        this.ll_djlx = v
        this.ll_lr = true
      },
      ll_djlx_add() {
        this.ll_djlx = {
          dict_code: undefined,
          time: undefined,
          jgms: undefined,
          type: undefined
        }
        this.ll_lr = true
      },
      // 获取字典
      getDictsList() {
        // 都需要的
        this.getDicts(this.query.szm).then(res => {
          this.dictionaries[this.query.szm] = Object.freeze(res.data)
        })
        this.getDicts('qz_cddw').then(res => {
          this.dictionaries['qz_cddw'] = Object.freeze(res.data)
        })
        // 拉练特殊情况
        switch (this.query.szm) {
          case 'll':
            this.getDicts('ll_djlx').then(res => {
              console.log(res);

              this.dictionaries['ll_djlx'] = Object.freeze(res.data)
            })
            break;
          default:
            break
        }
      },
      // 获取表格
      getTableOne() {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        let newDateList = new Set(); // 使用 Set 来去重
        getTable(this.handleQuery()).then(res => {
          // 部门重组
          const list = this.countParentId(res.data.dept)
          if (this.sjdwList.length === 0) {
            this.sjdwList = JSON.parse(JSON.stringify(list))
          }
          // 插入数量
          Object.freeze(list).forEach(item => {
            const error = {}
            let num = 0
            item.djdw.forEach(e => {
              const obj = e.dj
              if (e.dj) {
                Object.keys(obj).forEach(l => {
                  if (e.dj[l].length > this.len) {
                    this.len = e.dj[l].length
                  }
                  e.dj[l].forEach((s, ss) => {
                    if (s.sdd && s.sdd.listClass !== 'success') {
                      error[l] = error[l] ? error[l] + 1 : 1
                      num = num + 1
                    }
                  })
                })
              }
            })
            if (this.isLazyLoading) {
              res.data.dept[item.firstIndex] = {
                ...res.data.dept[item.firstIndex],
                count: item.count
              }
            }
            item.num = num
            item.error = error
          })
          this.sjdw = Object.freeze(list)
          this.cssz = JSON.parse(res.data.cssz)
          this.tableName = res.data.tableName
          this.$store.dispatch('tagsView/setMeta', {
            meta: {
              title: this.tableName
            }
          })
          this.dataList = Object.freeze(res.data.dept)
          this.isType = res.data.isType

          res.data.dept.forEach(e => {
            Object.keys(e.dj).forEach(date => {
              newDateList.add(date); // 直接将日期添加到 Set 中
            });
          });
          // 将 Set 转换为数组并排序
          newDateList = Array.from(newDateList).sort((a, b) => a.localeCompare(b));
        }).finally(f => {
          console.log(this.date[0], this.date[1]);
          if (this.date[0] == this.date[1]) {
            this.dateList = [this.date[0]]
          } else {
            this.dateList = newDateList
          }
          // if (this.query.szm == 'll') {
          // this.dateList = newDateList
          // } else {
          //   this.dateList = this.getDateList(this.date[0], this.date[1])
          // }
          this.$nextTick(() => {
            loading.close()
            this.$refs.Ltable.doLayout()
          })
        })
      },
      dateOptions(time) {
        const end = new Date(new Date().toLocaleDateString())
        end.setTime(end.getTime() + 3600 * 1000 * 24 - 1000)
        return time.getTime() > end.getTime()
      },
      isChildren(e, v) {
        const result = this.dictionaries[this.query.szm].find(item => item.dictCode === e)
        if (!v.isChildren) {
          return
        }
        this.datesShow = JSON.parse(v.children.value).includes(result.dictValue / 1)
        if (this.datesShow) {
          if (this.form.wgsj && this.form.wgsj[0] == null && this.form.wgsj[1] == null) {
            this.form.wgsj = undefined
          }
        } else {
          this.form.wgsj = [null, null]
        }
      },
      getUserlist() {
        listUser({
          pageNum: 1,
          pageSize: 100
        }).then(response => {
          this.userList = response.rows
        })
      },
      countParentId(arr) {
        const result = {}
        arr.forEach((item, index) => {
          if (!result[item.parentId]) {
            result[item.parentId] = {
              count: 1,
              firstIndex: index,
              parentId: item.parentId,
              parentName: item.parentName,
              djdw: [item]
            }
          } else {
            result[item.parentId].djdw.push(item)
            result[item.parentId].count++
          }
        })
        return Object.values(result)
      },
      handleQuery() {
        return {
          startTime: this.date[0] + ' 00:00:00',
          endTime: this.date[1] + ' 23:59:59',
          ...this.query
        }
      },

      // 日期列表
      getDateList(start, end) {
        let dateList = [];
        let currentDate = new Date(start);
        const endDate = new Date(end);
        while (currentDate <= endDate) {
          dateList.push(currentDate.toISOString().split('T')[0]);
          currentDate.setDate(currentDate.getDate() + 1);
        }
        return dateList;
      },
      // 上传数据
      postForm() {
        this.pLoading = true
        const api = {
          addRhtxdj,
          updateRhtxdj
        }
        const params = {
          ...this.form
        }
        if (this.query.szm === 'll' && this.ll_djlx_jh.length) {
          params.jgms = JSON.stringify(this.ll_djlx_jh)
        }
        params.wgsj = JSON.stringify(params.wgsj)
        let i
        this.cssz.forEach(item => {
          if (!params[item.name] && !i && item.isUp) {
            i = item.placeholder
          }
        })
        if (i) {
          this.pLoading = false
          return this.$message({
            message: i,
            type: 'error'
          })
        }

        api[params.post](params).then(res => {
          this.$message({
            message: res.msg,
            type: 'success'
          })
          this.dialogFormVisible = false
          this.getTableOne()
        }).finally(f => {
          this.Loading = false
          this.pLoading = false
        })
      },
      // 删除点检记录
      deleteDj() {
        this.pLoading = true
        delRhtxdj(this.form.rhtxdjId).then(res => {
          this.$message({
            message: res.msg,
            type: 'success'
          })
          this.dialogFormVisible = false
          this.getTableOne()
        }).finally(f => {
          this.pLoading = false
        })
      },
      // 新增-编辑数据
      addForm(value, post) {
        Object.keys(this.form).forEach(item => {
          this.form[item] = undefined
        })
        this.form['rhtxdjId'] = undefined
        switch (post) {
          case 'addRhtxdj':
            this.ll_djlx_jh = [];
            this.ll_djlx_i = null
            this.form.deptId = value.deptId
            if (this.query.szm === 'll') {
              this.form.ll_djlx = []
            }
            break
          case 'updateRhtxdj':
            Object.keys(this.form).forEach(item => {
              if (value[item]) {
                this.form[item] = value[item]
              }
            })
            if (this.query.szm === 'll') {
              this.ll_djlx_jh = JSON.parse(this.form.jgms)
            }
            var index = this.cssz.findIndex(obj => obj.name === 'dictCode')
            if (index !== -1 && this.cssz[index].children.value) {
              this.form.wgsj = this.form.wgsj && JSON.parse(this.form.wgsj)
              const result = this.dictionaries[this.query.szm].find(item => item.dictCode === this.form.dictCode)
              this.datesShow = this.cssz[index].children && JSON.parse(this.cssz[index].children.value).includes(result
                .dictValue / 1)
            }
            console.log(this.form);

            if (this.form.cddw) {
              this.form.cddw = this.form.cddw / 1
            }
            break
        }
        this.form['tableId'] = this.$route.params.id
        this.form['post'] = post
        this.dialogFormVisible = true
      },
      sjdwChange(value) {
        if (value.length === 0) {
          this.query.deptIds = []
        }
        this.getTableOne()
      },
      // 导出excel文本
      excel() {
        // elm 侧边提示 2024-11-18日之前和2024-11-19之后的的数据，不能同时导出需要分两次导出！
        if (this.query.szm === 'll') {
          this.$message({
            message: '2024-11-18日之前和2024-11-19之后的的数据，不能同时导出需要分两次导出！',
            type: 'info'
          })
        }
        this.download('/rhtx/dj/export', this.handleQuery(), `${this.tableName}_${new Date().getTime()}.xlsx`)
      }
    }
  }

</script>
<style lang="scss" scoped>
  .dj {
    margin: 20px 40px;

    .jb {
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .dj-table {
      margin-bottom: 20px;
    }

    .search {
      padding-bottom: 10px;
    }

  }

</style>
